$(function () {
    //检查时是否是分享出去的页面，添加悬浮按钮
    checkSharedPage();
   var desc =  $("#share_content").text();
    var _interval = null;
    wShareFn.Focus.init({
        ele: '#wShareBtn',
        opt: checkBaseShare(shareChannel),
        title : $('.article-title').text(),
        lookNum:$("#lookNum").val(),
        url : window.location.href,
        desc : desc,
        img:staticPath+"/front/mobile/v3/img/default/message-none.png"
    });
    commFocusFn();
    //处理主干图片
    dealImg();
    //评论交互
    function commFocusFn() {
        $('#commentInp').focus(function () { //获得焦点
            var _this = $(this);
            _this.parent().siblings('.external').hide();
            _this.next('#commentBtn').show();
            _this.parent('.inp-txt__wrap').css('width', '100% !important')
            _this.css({'width': '84%', 'line-height': '.96rem'});
            _interval = setInterval(function () {
                _this.scrollIntoView = _this.scrollIntoView || _this.scrollIntoViewIfNeeded;
                if (_this.scrollIntoView) {
                    _this.scrollIntoView(true);
                }
            }, 500);
        });
        $('#commentInp').blur(function () { //失去焦点
            var _this = $(this);
            clearInterval(_interval);
            _this.parent().siblings('.external').css('display', 'block');
            _this.next('#commentBtn').hide();
            _this.parent('.inp-txt__wrap').css('width', '45% !important')
            _this.css({'width': '90%', 'line-height': '1.5rem'});
        });
    }

    // 保存评论
    function saveTopicReply(context, targetReplyId, callback) {
        if(context==null||context==""){
            $.toast("评论内容不能为空");
            return;
        }
        var classId = $('#classId').val();
        var topicId = $('#topicId').val();
        var reply = {
            'classId': classId,
            'topicId': topicId,
            'content': context,
            'targetId': targetReplyId};
        reply = JSON.stringify(reply);
        $.ajax({
            url: baseloaction + "/mobile/uc/class/topic/ajax/save/reply",
            type:'post',
            data: reply,
            dataType: 'json',
            contentType:'application/json;charset=utf-8',
            success: function (response) {
                if (response.success) {
                    $.toast(response.message);
                    if ($.isFunction(callback)) {
                        callback();
                    }
                } else {
                    $.toast(response.message);
                }
            }
        })
    }

    // 重置评论框
    function resetCommentInp() {
      var commentInp = $("#commentInp");
        if(commentInp.length>0){
            $('#commentInp').css({'width': 'auto', 'line-height': '1.5rem'})
                .val('').attr('placeholder', '写评论').next('#commentBtn').hide();
            $('#commentInp').parent().siblings('.external').css('display', 'table-cell');
        }

    }

    // 重置评论框
    function resetCommentInpPop() {
        var copy = $('#commentInp-pop').data('copy');
        $('#commentInp-pop').val('').attr('placeholder', '写评论').data('target', copy);

    }

    // 更新评论总数 两个位置
    function updateReplyNum() {
        var regex = /[\d]+/g;
        var html = $('#reply-number-first small').html();
        var number = parseInt(regex.exec(html));
        number += 1;
        $('#reply-number-first small').html('(' + number + ')');
        $('#reply-number-second').html('<i class="icon iconfont icon-taolun" style="font-size: 0.9rem"></i> ' + number);
    }

    topicJbFn();

    //话题举报
    function topicJbFn() {
        $(document).on('click', '#topic-jubao-btn', function () {
            $.popup('.topicJubaoPopup');

            $('#topic-report-type li').click(function () {
                $(this).addClass('dc-active').siblings().removeClass('dc-active');
            });

            $('#submit-topic-report').click(function () {
                var reportType = $('#topic-report-type li.dc-active').data('type');
                var context = $('#topic-report-context').val();
                submitTopicReport(reportType, context);
            });

            $('#cancel-topic-report').click(function () {
                $('#topic-report-type li').eq(0).click();
                $('#topic-report-context').val('');
                // 注意解除绑定事件
                $('#cancel-topic-report').unbind('click');
                $('#submit-topic-report').unbind('click');
            });
        })
    }

    // 提交话题举报
    function submitTopicReport(reportType, context) {
        var topicId = $('#topicId').val();
        var params = {"topicId":topicId,'type': reportType, 'content': context};
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/mobile/uc/class/topic/ajax/save/report',
            type: 'post',
            data: params,
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                if (response.success) {
                    $.toast(response.message);
                    $('#cancel-topic-report').click();
                } else {
                    $.toast(response.message);
                }
            },
            error: function () {
                $.toast('系统繁忙，请稍候再试');
            }
        })
    }

    var _eventStr = $.device.ios ? 'click' : 'mousedown';
    $('body')
        .on(_eventStr, '#commentBtn', function () {
            var context = $('#commentInp').val();
            var targetReplyId = $('#commentInp').data('target') || 0;
            saveTopicReply(context, targetReplyId, function () {
                listTopicReply(1);
                resetCommentInp();
                updateReplyNum();
            });
        })
        .on('click', '#close-sub-topic-reply', function () {
            resetCommentInpPop();
        })
        .on('click', '#commentBtn-pop', function () {
          var  context  = $('#commentInp-pop').val();
          if(context.length<=0){
              $.toast('请输入评论');
              return;
          }
          var  targetId = $('#commentInp-pop').data('target');
            var  targetReplyId = targetId;
            if(targetId==null||targetId==undefined){
                targetReplyId =$("#reply-id").val();
          }
            saveTopicReply(context, targetReplyId, function () {
                setCommentInp();
                $('#commentInp-pop').val("");
                getChildReplyList(1);
            });
        })
        .on('click', '.allReplyPopup li.card-header', function () {
            if ($(this).hasClass('exclude')) {
                return;
            }
            var targetReplyId = $(this).data('target');
            var username = $(this).data('username');
            initCommentInpPop(targetReplyId, username);
        })
        .on('click', 'section.question-reply-item', function () { // 点击子评论时
            var targetReplyId = $(this).data('target');
            var username = $(this).data('username');
            initCommentInp(targetReplyId, username);
        })
        .on('click', 'i.comments', function () { // 点击主评论旁的消息图标时
            var targetReplyId = $(this).parent().data('target');
            var username = $(this).parent().data('username');
            initCommentInp(targetReplyId, username);
        })
        .on('click', 'div.teacherInfo-page__wrap, header.bar-nav', function (e) { // 点击非输入框区域时，使输入框恢复获取焦点前样式
            e = e || window.event;
            var $target = $(e.target);
            if ($target.hasClass('icon-message') ||
                $target.hasClass('question-reply-item') ||
                $target.attr('id') == 'commentInp' ||
                $target.parents('section.question-reply-item').length > 0) {
                return;
            }
            resetCommentInp();
        })
        .on('click', '#topic-like-btn', function () { // 点赞
            topicThumbsUp();
        })
        .on('click', 'a.allReplyBtn,a.closeReplyBtn', function () { //查看所有回复
            allReplyFn($(this).parent())
        }).on('click', '.topic-photo-popup', function () {
        var that =$(this);
        var imgs = that.parent().parent('div').find('img');
         openPhotoBrowser(that.next(),imgs);
        });
    // 初始化评论输入框样式
    function initCommentInp(targetReplyId, username) {
        $('#commentInp').focus();
        $('#commentInp').attr('placeholder', '@ ' + username).data('target', targetReplyId);
    }

    // 初始化评论输入框样式
    function initCommentInpPop(targetReplyId, username) {
        $('#commentInp-pop').focus();
        $('#commentInp-pop').attr('placeholder', '@ ' + username).attr('data-target', targetReplyId);
    }

    // 点赞话题
    function topicThumbsUp() {
        var topicId = $('#topicId').val();
        $.ajax({
            url: baseloaction + '/mobile/uc/class/topic/ajax/topic/like',
            data: {'topicId': topicId},
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    $.toast(response.message);
                    $("#likeNum").html(response.entity.likeNum);
                    if(response.entity.likeFlag){
                        $('.icon-love_fill').removeClass('hide');
                        $('.icon-xihuan').addClass('hide');
                    }else {
                        $('.icon-love_fill').addClass('hide');
                        $('.icon-xihuan').removeClass('hide');
                    }
                } else {
                    $.toast(response.message);
                }
            },
            error: function () {
                $.toast('系统繁忙，请稍候再试');
            }
        })
    }
    listTopicReply(1);
    // 加载评论
    function listTopicReply(pageNo) {
        var topicId = $('#topicId').val();
        var classId = $('#classId').val();
        var params = {"topicId":topicId,"classesId":classId,"rootId":0};
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/class/topic/ajax/list/reply',
            contextId: 'topic-reply-list',
            pageNo: pageNo,
            pageCall: listTopicReply,
            params: params,
            callback: function (pageNo) {
            }
        });
    }
    //禁止ios浏览器页面上下滚动 (橡皮筋效果)
    iosTrouchFn(document.querySelector('.native-scroll'));
    //控制话题图片大小，并且添加点击查看试卷
    function dealImg() {
        var images = $('#share_content img');
        if (images.length > 0) {
            for (var i = 0; i < images.length; i++) {
                var _this=$(images[i]);
                if(parseInt(_this.css('width'))>=320){
                    _this.css({'max-width': '100%','width': '100%','height': 'auto'});
                }
            }
            _this.addClass('topic-trunk-photo-popup');
        }
        $('#share_content').on('click','.topic-trunk-photo-popup',function(){
            openPhotoBrowser($(this),$('.topic-trunk-photo-popup'))
        })
    }

    /**
     * 查看全部评论
     */
    function allReplyFn(obj) {
        $.popup('.allReplyPopup');

        var targetId = obj.data("target");
        var toUserId = $("#reply-userid-"+targetId).attr("touserid");
        var userName = $("#reply-user-"+targetId).html();

        $("#reply-id").val(targetId);
        $("#reply-user").html(userName);
        $("#reply-img").attr("src",document.getElementById("reply-img-"+targetId).src);
        $("#reply-date").html($("#reply-date-"+targetId).html());
        $("#reply-context").html($("#reply-context-"+targetId).html());

        $("#save-reply-targetId-pop").val(targetId);
        setCommentInp("commentInp-pop",userName);
        getChildReplyList(1);
    }
    //设置输入框placeholder属性
    function setCommentInp(inputId, userName) {
        $("#"+inputId).attr("placeholder", "@"+ userName +"：").val('');
    }

    //查看全部回复
    function getChildReplyList(pageNo) {
        var params = {"id":$("#reply-id").val()};
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/uc/class/topic/ajax/all/reply',//请求url
            contextId:'allreply-list-content',//请求成功后数据内容添加的地方
            pageNo:pageNo,//页面码，可以不传
            pageCall:getChildReplyList,//分页方法（一般调用自身）
            params:params,//查询参数
            callback:function (pageNo) {

            }
        });
    }
});
